export default class RecorderManager {
    constructor(url) {
        this.url = url;
        this.isRecording = false;
        this.audioContext = null;
        this.mediaStream = null;
        this.scriptProcessor = null;
        
        // Callbacks
        this.onStart = null;
        this.onStop = null;
        this.onFrameRecorded = null;
    }

    async start({ sampleRate = 16000, frameSize = 2048 } = {}) {
        if (this.isRecording) return;
        
        try {
            this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)({
                sampleRate: sampleRate
            });

            const mediaStreamSource = this.audioContext.createMediaStreamSource(this.mediaStream);
            this.scriptProcessor = this.audioContext.createScriptProcessor(frameSize, 1, 1);

            this.scriptProcessor.onaudioprocess = (e) => {
                if (!this.isRecording) return;

                const inputBuffer = e.inputBuffer;
                const inputData = inputBuffer.getChannelData(0);
                
                // Convert float32 to int16
                const int16Data = new Int16Array(inputData.length);
                for (let i = 0; i < inputData.length; i++) {
                    int16Data[i] = Math.min(1, inputData[i]) * 0x7FFF;
                }

                if (this.onFrameRecorded) {
                    this.onFrameRecorded({
                        isLastFrame: false,
                        frameBuffer: int16Data.buffer
                    });
                }
            };

            mediaStreamSource.connect(this.scriptProcessor);
            this.scriptProcessor.connect(this.audioContext.destination);
            
            this.isRecording = true;
            if (this.onStart) this.onStart();
        } catch (error) {
            console.error('Failed to start recording:', error);
            throw error;
        }
    }

    stop() {
        if (!this.isRecording) return;

        this.isRecording = false;

        if (this.scriptProcessor) {
            this.scriptProcessor.disconnect();
            this.scriptProcessor = null;
        }

        if (this.mediaStream) {
            this.mediaStream.getTracks().forEach(track => track.stop());
            this.mediaStream = null;
        }

        if (this.audioContext) {
            this.audioContext.close();
            this.audioContext = null;
        }

        if (this.onFrameRecorded) {
            // Send an empty buffer as the last frame
            this.onFrameRecorded({
                isLastFrame: true,
                frameBuffer: new ArrayBuffer(0)
            });
        }

        if (this.onStop) this.onStop();
    }
} 